package com.mb.app.controller;


import com.mb.app.domain.*;
import com.mb.app.service.*;
import com.mb.common.controller.BaseController;
import com.mb.common.domain.ZtreeNodeDo;
import com.mb.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zwl
 * @program
 * @description 商品信息管理
 * @date 2019-03-22 13:01
 **/
@Controller
@RequestMapping("/app/product")
@Slf4j
public class ProductInfoController extends BaseController {

    @Autowired
    private ITbProductClassService productClassService;
    
    @Autowired
    private ITbProductInfoService productInfoService;

    @Autowired
    private ITbColorCfgService colorCfgService;

    @Autowired
    private ITbSpecsCfgService specsCfgService;

    @Autowired
    private ITbProductColorService productColorService;

    @Autowired
    private ITbProductSpecsService productSpecsService;

    @Autowired
    private ITbProductPriceService productPriceService;

    @Autowired
    private ITbProductShipFeeCfgService productShipFeeCfgService;

    @Autowired
    private ISysAreaCoordService sysAreaCoordService;

    @GetMapping("/index")
    String index(Model model){
        // 查询分类信息
        Map<String,Object> map = new HashMap<String,Object>();
        List<TbProductClass> productClasses = productClassService.getProductClassInfoList(map);
        model.addAttribute("productClasses",productClasses);
        return "/app/product/product_list";
    }


    @GetMapping("/selectIndex")
    String selectIndex(Model model){
        // 查询分类信息
        Map<String,Object> map = new HashMap<String,Object>();
        List<TbProductClass> productClasses = productClassService.getProductClassInfoList(map);
        model.addAttribute("productClasses",productClasses);
        return "/app/product/selectProduct_list";
    }

    @GetMapping("/selectIndexBanner")
    String selectIndexBanner(Model model){
        // 查询分类信息
        Map<String,Object> map = new HashMap<String,Object>();
        List<TbProductClass> productClasses = productClassService.getProductClassInfoList(map);
        model.addAttribute("productClasses",productClasses);
        return "/app/banner/selectProduct_list";
    }

    @ResponseBody
    @GetMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        // 时间截取
        String createTime = (String) params.get("createTime");
        if (StringUtils.isNotEmpty(createTime)) {
            params.put("startTime", DateUtils.parse(createTime.substring(0,10),DateUtils.DATE_PATTERN));
            params.put("endTime",createTime.substring(13,23)+" 23:59:59");
        }
        Query query = new Query(params);
        List<TbProductInfo> list = productInfoService.queryList(query);
        int total = productInfoService.count(query);
        PageUtils pageUtils = new PageUtils(list, total);
        return pageUtils;
    }

    @GetMapping("/add")
    String add(Model model){
        // 查询应用信息
        Map<String,Object> map = new HashMap<String,Object>();
        List<TbProductClass> productClasses = productClassService.getProductClassInfoList(map);
        model.addAttribute("productClasses",productClasses);
        // 查询颜色属性配置
        List<TbColorCfg> colorCfgs = colorCfgService.queryList(map);
        model.addAttribute("colorCfgs",colorCfgs);
//        // 查询规格参数属性配置
//        List<TbSpecsCfg> specsCfgs = specsCfgService.queryList(map);
//        model.addAttribute("specsCfgs",specsCfgs);
        return "/app/product/product_add";
    }


    @ResponseBody
    @PostMapping("/save")
    public R save(TbProductInfo TbProductInfo,@RequestParam(value = "colorIds[]", required = false) String[] colorIds,@RequestParam(value = "specsIds[]", required = false) String[] specsIds ){
        TbProductInfo.setAddUserId(getUserId());
        int result = productInfoService.save(TbProductInfo,colorIds,specsIds);
        return R.ok();
    }


    @ResponseBody
    @PostMapping("/remove")
    public R remove(@RequestParam("productId") Long productId, HttpServletRequest request){
        Long delUserId = getUserId();
        int result = productInfoService.remove(productId,delUserId);
        return R.ok();
    }

    @GetMapping("/dtl/{productId}")
    String dtl(@PathVariable("productId") Long productId, Model model){
        model.addAttribute("productInfo",productInfoService.getDtl(productId));
        Map<String,Object> map = new HashMap<String,Object>();
        List<TbProductClass> productClasses = productClassService.getProductClassInfoList(map);
        map.put("product_id",productId);
        model.addAttribute("productClasses",productClasses);
        model.addAttribute("colorList",productColorService.getProductColorList(map));
        model.addAttribute("specsList",productSpecsService.getProductSpecsList(map));
        return "/app/product/product_info";
    }


    @GetMapping("/edit/{productId}")
    String edit(@PathVariable("productId") Long productId, Model model){
        model.addAttribute("productInfo",productInfoService.getDtl(productId));
        Map<String,Object> map = new HashMap<String,Object>();
        List<TbProductClass> productClasses = productClassService.getProductClassInfoList(map);
        model.addAttribute("productClasses",productClasses);
        // 查询颜色属性配置
        List<TbColorCfg> colorCfgs = colorCfgService.queryList(map);
        model.addAttribute("colorCfgs",colorCfgs);
        // 查询规格参数属性配置
        List<TbSpecsCfg> specsCfgs = specsCfgService.queryList(map);
        model.addAttribute("specsCfgs",specsCfgs);
        MethodServiceUtils md = new MethodServiceUtils();
        model.addAttribute("methodServiceColor",md);
        map.put("product_id",productId);
        model.addAttribute("colorList",productColorService.getProductColorList(map));
        List<TbProductSpecs> specsList =  productSpecsService.getProductSpecsList(map);
        if (specsList != null) {
            String specsNames = "";
            for (int i =0; i < specsList.size(); i++) {
                TbProductSpecs productSpecs = specsList.get(i);
                if (i == 0) {
                    specsNames = productSpecs.getSpecsName();
                }else {
                    specsNames = specsNames +","+ productSpecs.getSpecsName();
                }
            }
            model.addAttribute("specsNames",specsNames);
        }
        model.addAttribute("specsList",productSpecsService.getProductSpecsList(map));
        return "/app/product/product_edit";
    }

    @ResponseBody
    @PostMapping("/update")
    public R update(TbProductInfo TbProductInfo, @RequestParam(value = "colorIds[]", required = false) String[] colorIds,@RequestParam(value = "specsIds[]", required = false) String[] specsIds){
        TbProductInfo.setUpdateUserId(getUserId());
        int result = productInfoService.update(TbProductInfo,colorIds,specsIds);
        return R.ok();
    }

    /**
     *商品名称是否存在
     */
    @PostMapping("/productInfoNameExit")
    @ResponseBody
    boolean productInfoNameExit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !productInfoService.productInfoNameExit(params);
    }

    @ResponseBody
    @PostMapping("/status")
    public R remove(@RequestParam("productId") Long productId,@RequestParam("productStatus") Integer productStatus, HttpServletRequest request){
        int result = productInfoService.status(productId,productStatus);
        return R.ok();
    }

    @GetMapping("/classTree")
    String classTree(Model model){
        return "/app/product/classTree";
    }

    @ResponseBody
    @PostMapping("/getTreeList")
    public List<ZtreeNodeDo> getTreeList(){
        Map<String,Object> map = new HashMap<String, Object>();
        List<TbProductClass> tbProductClasses = productClassService.getProductClassInfoList(map);
        List<ZtreeNodeDo> ztreeNodeDos = new ArrayList<ZtreeNodeDo>();
        if (tbProductClasses.size()> 0) {
            for (TbProductClass productClass : tbProductClasses) {
                ZtreeNodeDo ztreeNodeDo = new ZtreeNodeDo();
                ztreeNodeDo.setId(productClass.getClassId());
                ztreeNodeDo.setpId(productClass.getParentClassId());
                ztreeNodeDo.setName(productClass.getClassName());
                ztreeNodeDo.setT(productClass.getClassName());
                if (productClass.getParentClassId() == 0) {
                    ztreeNodeDo.setOpen(true);
                }
                ztreeNodeDos.add(ztreeNodeDo);

            }
        }
        return ztreeNodeDos;
    }

    /*******************************************************商品规格树***************************************************************************************************************/
    @GetMapping("/specsTree")
    String specsTree(Model model,@RequestParam(value = "specsIds", required = false) String specsIds){
        String[] specsId = null;
        if (specsIds != null) {
            specsId = specsIds.split(",");
        }
        model.addAttribute("specsIds",specsId);
        return "/app/product/eleTree";
    }

    @ResponseBody
    @RequestMapping("/getSpecsTreeList")
    public List<ZtreeNodeDo> getSpecsTreeList(@RequestBody TbSpecsCfg tbSpecsCfg){
        Map<String,Object> map = new HashMap<String, Object>();
        if (tbSpecsCfg != null && tbSpecsCfg.getSpecsId() == null) {
            map.put("pId",0);
        }else {
            map.put("pId",tbSpecsCfg.getSpecsId());
        }
        List<TbSpecsCfg> specsCfgs = specsCfgService.getSpecsList(map);
        List<ZtreeNodeDo> ztreeNodeDos = new ArrayList<ZtreeNodeDo>();
        if (specsCfgs.size()> 0) {
            for (TbSpecsCfg specsCfg : specsCfgs) {
                ZtreeNodeDo ztreeNodeDo = new ZtreeNodeDo();
                ztreeNodeDo.setId(specsCfg.getSpecsId());
                ztreeNodeDo.setName(specsCfg.getSpecsName());
                map.put("pId",specsCfg.getSpecsId());
                List<TbSpecsCfg> specsList = specsCfgService.getSpecsList(map);
                if (specsList != null && specsList.size() > 0 ) {
                    ztreeNodeDo.setParent(true);
                }else {
                    ztreeNodeDo.setParent(false);
                }
                ztreeNodeDos.add(ztreeNodeDo);
            }
        }
        return ztreeNodeDos;
    }

    public ZtreeNodeDo getZtreeNodeDo(TbSpecsCfg specsCfg) {
        ZtreeNodeDo ztreeNodeDo = new ZtreeNodeDo();
        ztreeNodeDo.setId(specsCfg.getSpecsId());
        ztreeNodeDo.setpId(specsCfg.getpId());
        ztreeNodeDo.setName(specsCfg.getSpecsName());
        ztreeNodeDo.setT(specsCfg.getSpecsName());
        return ztreeNodeDo;
    }


    /***************************************************************************************************************************************************************************/

    /**
     * 商品价格管理
     * @param productId
     * @param model
     * @return
     */
    @GetMapping("/getProductPrice/{productId}")
    String getProductPrice(@PathVariable("productId") Long productId, Model model){
        //  获取商品价格
        Map<String,Object> productPriceMap = new HashMap<String, Object>();
        productPriceMap.put("productId",productId);
        List<TbProductPrice> productPrices = productPriceService.getProductPriceList(productPriceMap);
        model.addAttribute("productPrices",productPrices);
        model.addAttribute("productId",productId);
        return "/app/product/price";
    }

    /**
     * 修改商品价格
     * @param tbProductPrice
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/updatePrice")
    public R updatePrice(@RequestBody TbProductPrice tbProductPrice,HttpServletRequest request){
        tbProductPrice.setUpdateUserId(getUserId());
        boolean istre =  productPriceService.updateById(tbProductPrice);
        if (istre) {
            return R.ok();
        }else {
            return R.error();
        }
    }
    /***************************************************************************************************************************************************************************/
    /**
     * 运费管理
     * @param productId
     * @param model
     * @return
     */
    @GetMapping("/getProductShipFee/{productId}")
    String getProductShipFee(@PathVariable("productId") Long productId, Model model){
        //  获取商品运费配置
        Map<String,Object> productPriceMap = new HashMap<String, Object>();
        productPriceMap.put("product_id",productId);
        List<TbProductShipFeeCfg> productShipFeeCfgs = productShipFeeCfgService.getProductShipList(productPriceMap);
        model.addAttribute("productShipFeeCfgs",productShipFeeCfgs);
        model.addAttribute("productId",productId);
        return "/app/product/shipFee";
    }

    @ResponseBody
    @PostMapping("/updateShipFee")
    public R updateShipFee(@RequestBody TbProductShipFeeCfg tbProductShipFeeCfg){
        int istre =  productShipFeeCfgService.save(tbProductShipFeeCfg,getUserId());
        if (istre>0) {
            return R.ok();
        }else {
            return R.error();
        }
    }

    @ResponseBody
    @PostMapping("/deleteShipFee")
    public R deleteShipFee(@RequestBody List<TbProductShipFeeCfg> tbProductShipFeeCfgs){
        int istre =  productShipFeeCfgService.deleteShipFee(tbProductShipFeeCfgs,getUserId());
        if (istre>0) {
            return R.ok();
        }else {
            return R.error();
        }
    }

    @ResponseBody
    @PostMapping("/selectShipFee")
    public R selectShipFee(@RequestBody TbProductShipFeeCfg productShipFeeCfg){
        Map<String,Object> map = new HashMap<String, Object>();
        List<SysAreaCoord> sysAreaCoords = new ArrayList<SysAreaCoord>();
        if (productShipFeeCfg != null && productShipFeeCfg.getAreaIds() != null && productShipFeeCfg.getAreaIds() != "") {
            String[] areaIds = productShipFeeCfg.getAreaIds().split(",");
            for(int j = 0; j < areaIds.length; j++) {
                // 根据 区域编号 查询
                SysAreaCoord sysAreaCoord = sysAreaCoordService.selectById(areaIds[j]);
                if(sysAreaCoord != null) {
                    sysAreaCoords.add(sysAreaCoord);
                }
            }
        }
        map.put("data",sysAreaCoords);
        return  R.ok(map);
    }

    @ResponseBody
    @PostMapping("/getAreaCoord")
    public R getAreaCoord(@RequestBody TbProductShipFeeCfg tbProductShipFeeCfg){
        Map<String,Object> map = new HashMap<String, Object>();
        // 查询所有 运费配置TbProductShipFeeCfgMapper
        map.put("product_id",tbProductShipFeeCfg.getProductId());
        List<TbProductShipFeeCfg> tbProductShipFeeCfgs = productShipFeeCfgService.getProductShipList(map);
        List<String> sysAreaCoord = new ArrayList<String>();
        if (tbProductShipFeeCfgs.size() > 0) {
            for (int i = 0; i < tbProductShipFeeCfgs.size(); i++) {
                TbProductShipFeeCfg tbShipFeeCfg = tbProductShipFeeCfgs.get(i);
                if(tbShipFeeCfg.getAreaIds() != null && tbShipFeeCfg.getAreaIds() != "") {
                    String[] areaIds = tbShipFeeCfg.getAreaIds().split(",");
                    for(int j = 0; j < areaIds.length; j++) {
                        sysAreaCoord.add(areaIds[j]);
                    }
                }
            }
        }
        // 查询省份信息
        map.put("level",1);
        map.put("list",sysAreaCoord);
        List<SysAreaCoord> sysAreaCoords = sysAreaCoordService.getSysAreaCoord(map);
        map.put("data",sysAreaCoords);
        return  R.ok(map);
    }

}
